import { Injectable, ConflictException, NotFoundException, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { User } from './entities/user.entity';
import { CreateUserDto } from './dto/create-user.dto';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  async create(createUserDto: CreateUserDto): Promise<User> {
    // 检查工号是否已存在
    const existingUser = await this.usersRepository.findOne({
      where: { employeeId: createUserDto.employeeId },
    });
    
    if (existingUser) {
      throw new ConflictException('工号已存在');
    }

    // 加密密码
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(createUserDto.password, saltRounds);

    // 创建用户
    const user = this.usersRepository.create({
      employeeId: createUserDto.employeeId,
      password: hashedPassword,
      realName: createUserDto.realName,
      role: createUserDto.role || 'user',
    });

    return await this.usersRepository.save(user);
  }

  async validateUser(employeeId: string, password: string): Promise<User> {
    const user = await this.usersRepository.findOne({
      where: { employeeId },
      select: ['id', 'employeeId', 'password', 'realName', 'role'],
    });

    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      throw new UnauthorizedException('密码错误');
    }

    // 返回用户信息（排除密码）
    const { password: _, ...result } = user;
    return result as User;
  }

  async findById(id: number): Promise<User> {
    const user = await this.usersRepository.findOne({ where: { id } });
    if (!user) {
      throw new NotFoundException('用户不存在');
    }
    return user;
  }

  async findByEmployeeId(employeeId: string): Promise<User> {
    const user = await this.usersRepository.findOne({ where: { employeeId } });
    if (!user) {
      throw new NotFoundException('用户不存在');
    }
    return user;
  }

  async findAll(): Promise<User[]> {
    return await this.usersRepository.find();
  }

  async remove(id: number): Promise<void> {
    const user = await this.usersRepository.findOne({ where: { id } });
    if (!user) {
      throw new NotFoundException('用户不存在');
    }
    await this.usersRepository.remove(user);
  }

  // 创建默认管理员用户（如果不存在）
  async createDefaultAdmin() {
    try {
      const adminExists = await this.usersRepository.findOne({
        where: { employeeId: 'admin001' },
      });

      if (!adminExists) {
        const saltRounds = 10;
        const hashedPassword = await bcrypt.hash('admin123', saltRounds);
        
        const adminUser = this.usersRepository.create({
          employeeId: 'admin001',
          password: hashedPassword,
          realName: '系统管理员',
          role: 'admin',
        });

        await this.usersRepository.save(adminUser);
        console.log('✅ 默认管理员用户创建成功');
      }
    } catch (error) {
      console.error('创建默认管理员用户失败:', error.message);
    }
  }
}